package com.springboot.frame.starter.cors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * Cors 的spring-boot启动器
 * 实现基本的跨域请求
 * 2.4.0 通多配置
 *
 * @author liheng
 * @Override public void addCorsMappings(CorsRegistry registry) {
 * registry.addMapping("/**")
 * // SpringBoot2.4.0 [allowedOriginPatterns]代替[allowedOrigins]
 * .allowedOriginPatterns("*")
 * .allowedMethods("*")
 * .maxAge(3600)
 * .allowCredentials(true);
 * }
 *
 * @author liheng
 */
@Configuration
@EnableConfigurationProperties(CorsProperties.class)
@ConditionalOnProperty(name = "web.cors.enabled")
@ConditionalOnClass(UrlBasedCorsConfigurationSource.class)
public class CorsAutoConfiguration {

  /**
   * cors配置参数
   */
  private final CorsProperties properties;

  @Autowired
  public CorsAutoConfiguration(CorsProperties properties) {
    this.properties = properties;
  }

  private CorsConfiguration buildConfig() {
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    // 允许任何域名使用
    corsConfiguration.addAllowedOriginPattern(properties.getAllowedOrigins());
    corsConfiguration.addAllowedOrigin("null");
    // allowCredential 需设置为true
    corsConfiguration.setAllowCredentials(true);
    // 允许任何头
    corsConfiguration.addAllowedHeader(properties.getAllowedHeaders());
    // 允许任何方法（post、get等）
    corsConfiguration.addAllowedMethod(properties.getAllowedMethods());
    return corsConfiguration;
  }

  @Bean
  public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    // 对接口配置跨域设置
    source.registerCorsConfiguration("/**", buildConfig());
    return new CorsFilter(source);
  }
}
